<?php

use Yaf\Registry;

class IndexController extends \Our\Controller_AbstractIndex {


    private $__rabbitConfig,$__rabbit_exchange_name,$__rabbit_queue_name,$__rabbit_route_key;

    private function dealTime($time)
    {
        if (empty($time)) {
            return [];
        }
        $time = json_decode($time, true);
        $weekArray = array('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun');
        $chineseWeek = array('Mon' => '周一', 'Tue' => '周二', 'Wed' => '周三', 'Thurs' => '周四', 'Fri' => '周五', 'Sat' => '周六', 'Sun' => '周日');

        $newTimesValue = [];

        foreach ($time as $week => $item) {

            if(!$item){
                continue;
            }

            foreach ($item as $it){
                $t = explode('-', $it);        //每天的营业时间点
                sort($t);  //对时间进行排序

                $nextDay = str_replace(':', '.', $t[1]);

                if($nextDay > 24){
                    $nextDay = explode(':', $t[1]);
                    $nextDay[0] = $nextDay[0] - 24;
                    $nextDay[0] = '次日' . $nextDay[0];
                    $t[1] = implode(':', $nextDay);
                }

                $time2time = implode(' ~ ', $t);

                $index = array_search($week, $weekArray);

                if(isset($newTimesValue[$time2time])){
                    $newTimesValue[$time2time][] = $index;
                }else{
                    $newTimesValue[$time2time] = [$index];
                }
            }
        }

        if(!$newTimesValue){
            return [];
        }

        $result = [];

        foreach ($newTimesValue as $key => $value){

            $week = [];
            $count = $value[count($value) - 1];
            $kIndex = 0;
            $allIs = 0;//是否执行到尽头

            foreach ($value as $k => $val){

                if($k < $kIndex){
                    continue;
                }

                $num = 0;

                for ($index = $k; $index < $count; $index++){
                    $kIndex ++;

                    if($value[$index] + 1 == $value[$index + 1]){
                        $num ++;
                    }else{
                        break;
                    }

                    if($value[$index + 1] == $count){
                        $allIs = 1;
                    }
                }

                if($num == 0){
                    $week[] = $chineseWeek[$weekArray[$val]];
                }else if($num == 1){
                    $week[] = $chineseWeek[$weekArray[$val]];
                    $week[] = $chineseWeek[$weekArray[$val + 1]];
                }else{
                    $week[] = $chineseWeek[$weekArray[$val]] . ' ~ ' .$chineseWeek[$weekArray[$val + $num]];
                }

                if($allIs){
                    break;
                }
            }

            $result[] = implode('、', $week) . ' ' . $key;
        }

        return $result;
    }


    protected static function isBusiness($time)
    {

        $isBusiness = false;
        $times = json_decode($time, true);
        $weekArray = array('Sun', 'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat'); //周几数组

        $now = time(); //现在时间
        $date = date('Y-m-d',$now);
        $nowStr = strtotime(date('Y-m-d H:i',$now));

        $index = date('w',$now);                //当天索引
        $preIndex = $index === 0 ? 6 : ($index - 1);  //上一天索引
        $week = $weekArray[$index];
        $preWeek = $weekArray[$preIndex];

        //首先判断前一天是否存在跨天营业时间
        $tempTime = [];
        foreach ($times[$preWeek] as $vo) {
            $vo = str_replace('\r', '', $vo);
            list($start,$end) = explode('-', $vo);
            if($end>24){ //存在跨天,获取跨天营业时间
                list($hour,$sec) = explode(':', $end);
                $foramtHour = date('Y-m-d', strtotime('+1 days')).' '.($hour - 24).':'.$sec;
                $tempTime[] = [strtotime(date('Y-m-d '.$start)),strtotime($foramtHour)];
            }
        }

        if(!empty($tempTime)){
            foreach ($tempTime as $vo) {
                if($nowStr<=$vo[1] && $nowStr>=$vo[0]){  //现在时间在昨天的跨天营业时间内
                    $isBusiness = true;
                    break;
                }
            }
            if($isBusiness){
                return $isBusiness;
            }
        }
        //判断当天时间
        $current = $times[$week];
        if (!empty($current)) {
            foreach ($current as $item) {
                $item = str_replace('\r', '', $item);
                list($start,$end) = explode('-', $item);         //08:00-22:00
                $start = strtotime($date.' '.$start);
                $end = strtotime($date.' '.$end);
                if ($nowStr >= $start && $nowStr <= $end) {
                    $isBusiness = true;
                    break;
                }
            }
        }
        return $isBusiness;
    }


    function glob2foreach($path, $include_dirs = false)
    {
        $path = rtrim($path, '/*');
        if (is_readable($path)) {
            $dh = opendir($path);
            while (($file = readdir($dh)) !== false) {
                if (substr($file, 0, 1) == '.')
                    continue;
                $rfile = "{$path}/{$file}";
                if (is_dir($rfile)) {
                    $sub = $this->glob2foreach($rfile, $include_dirs);
                    while ($sub->valid()) {
                        yield $sub->current();
                        $sub->next();
                    }
                    if ($include_dirs)
                        yield $rfile;
                } else {
                    yield $rfile;
                }
            }
            closedir($dh);
        }
    }


    public function indexAction() {

        throw new \Exception('dddd',2222222);
        exit;
        // 使用
        $glob = $this->glob2foreach('/www');
        while ($glob->valid())
        {

            // 当前文件
            $filename = $glob->current();

            // 这个就是包括路径在内的完整文件名了
            echo $filename.PHP_EOL;

            // 指向下一个，不能少
            $glob->next();
        }

        exit;

        $str = '{"Mon":["08:00-12:00","15:00-15:30","20:00-30:00"],"Tue":["08:00-12:00","15:00-18:30","20:00-30:00"],"Wed":["08:00-12:00","15:00-15:30","20:00-30:00"],"Thurs":["08:00-12:00","15:00-15:30","20:00-30:00"],"Fri":["08:00-12:00","15:00-15:30","20:00-30:00"],"Sat":["08:00-12:00","15:00-15:30","20:00-30:00"],"Sun":["08:00-12:00","15:00-15:30","20:00-30:00"]}';
//        $str = '{"Mon":["08:00-22:30"],"Tue":["08:00-22:30"],"Wed":["08:00-21:00"],"Thurs":["08:00-21:00"],"Fri":["08:00-22:30"],"Sat":["08:00-22:30"],"Sun":["08:00-22:30"]}';
        var_dump(date('Y-m-d H:i:s'),self::isBusiness($str),$this->dealTime($str));exit;
        $amountVip = 0.01;
        $discount = 9.9;

        $default = $amountVip * ($discount / 10);

        $discountVipPrice = (float)sprintf('%.2f',$default);
        $discountVipPriceDec = $amountVip - $discountVipPrice;
        $discountVipPrice2 = round($default, 2);
        echo json_encode([$amountVip,$discount,$default,$discountVipPrice,$discountVipPriceDec,$discountVipPrice2]);

        exit;
    }

    public function init()
    {
        $this->__rabbitConfig = Registry::get('config')->rabbit->toArray();

        $this->__rabbit_exchange_name = 'test_exchange';
        $this->__rabbit_queue_name = 'test_queue';
        $this->__rabbit_route_key = 'test_route_key_001';
    }

    /**
     * php /www/yaf-examples/yaf-test/public/cli.php request_uri=/index/rabbitConsumer
     *
     * @throws AMQPChannelException
     * @throws AMQPConnectionException
     * @throws AMQPEnvelopeException
     * @throws AMQPExchangeException
     * @throws AMQPQueueException
     */
    public function rabbitConsumerAction(){
        //创建连接和channel
        $conn = new AMQPConnection($this->__rabbitConfig);
        if (!$conn->connect()) {
            die("Cannot connect to the broker!\n");
        }
        $channel = new AMQPChannel($conn);

        //创建交换机
        $ex = new AMQPExchange($channel);
        $ex->setName($this->__rabbit_exchange_name);
        $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型
        $ex->setFlags(AMQP_DURABLE); //持久化
        echo "Exchange Status:".$ex->declare()."\n";

        //创建队列
        $q = new AMQPQueue($channel);
        $q->setName($this->__rabbit_queue_name);
        $q->setFlags(AMQP_DURABLE); //持久化
        echo "Message Total:".$q->declare()."\n";

        //绑定交换机与队列，并指定路由键
        echo 'Queue Bind: '.$q->bind($this->__rabbit_exchange_name, $this->__rabbit_route_key)."\n";

        //阻塞模式接收消息
        echo "Message:\n";
        $q->consume('processMessage');
//        $q->consume('processMessage', AMQP_AUTOACK); //自动ACK应答
        $conn->disconnect();
    }


    /**
     * php /www/yaf-examples/yaf-test/public/cli.php request_uri=/index/rabbitPublisher
     *
     * @throws AMQPChannelException
     * @throws AMQPConnectionException
     * @throws AMQPExchangeException
     */
    public function rabbitPublisherAction(){
        //创建连接和channel
        $conn = new AMQPConnection($this->__rabbitConfig);
        if (!$conn->connect()) {
            die("Cannot connect to the broker!\n");
        }
        $channel = new AMQPChannel($conn);

        //创建交换机对象
        $ex = new AMQPExchange($channel);
        $ex->setName($this->__rabbit_exchange_name);

        //发送消息
        //$channel->startTransaction(); //开始事务
        for($i=0; $i<500; $i++){
            sleep(1);//休眠1秒
            //消息内容
            $message = [
                'msg' => date("h:i:sa").' -> hello world!',
                'index' => $i
            ];

            if($ex->publish(json_encode($message), $this->__rabbit_route_key)){
                echo "Send Message SUCCESS : ".$i."\n";
            }else{
                echo "Send Message FAILED : ".$i."\n";
//                $channel->rollbackTransaction();
            }
        }
        //$channel->commitTransaction(); //提交事务

        $conn->disconnect();
    }
}

/**
 * 消费回调函数
 * 处理消息
 */
function processMessage($envelope, $queue) {
    $msg = $envelope->getBody();
    echo $msg."\n"; //处理消息
    $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答
}